var app = getApp();
var area = require('../../utils/lib/area.js');
var utils = require('../../utils/shop/formatShop.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    //用于收货地址展示用
    objectMultiArray: [],   //展示数据
    multiIndex: [0, 0, 0],  //选择数据

    //用于收货地址选择用
    change_objectMultiArray: [],  //选择数据
    change_multiIndex: [0, 0, 0], //改变的收货地址对应列的下标

    //地址数据
    address_info: {
      Users_ID: '',
      User_ID: 0,
      Address_ID: 0,  //地址id  编辑时有用
      Address_Name: '',
      Address_Mobile: '',
      Address_Province: 0,  //为id
      Address_City: 0,      //为id
      Address_Area: 0,      //为id
      Address_Town: 0,
      Address_Detailed: '',
      Address_Is_Default: 0  //是否为默认地址
    },
    // 街道信息
    t_arr: [],
    t_index: 0,

    is_first_add: false,   //是否为该用户要添加的第一条收货地址

    from_page: '' //来源页面  checkout(需设置checkout页面的back_address_id)、addresslist(不需操作)
  },

  // 街道信息回到,t_area 替换掉
  address_town: function () {
    app.http_req({ act: 'get_town', 'a_id': this.data.address_info.Address_Area }, app.globalData.init.api_url, 'POST', res => {
      if (res.errorCode == 0) {
        var t_arr = [];
        var t_index = 0;
        var idx = 0;
        for (var i in res.data) {
          for (var j in res.data[i]) {
            t_arr.push({ 'id': j, 'name': res.data[i][j] });
            if (j == this.data.address_info.Address_Town) {
              t_index = idx;
            }
            idx++;
          }
        }
        this.setData({
          t_arr: t_arr,
          t_index: t_index
        })
      }
    });
  },

  // 乡镇地址 点击确定
  t_pickerChange: function (e) {
    this.setData({
      t_index: e.detail.value,
      'address_info.Address_Town': this.data.t_arr[e.detail.value]['id']
    })
  },

  //处理省市区联动信息
  addressChange: function (columnValue) {
    var p_arr = this.data.change_objectMultiArray[0];
    var p_id = p_arr[columnValue[0]]['id'];
    var c_arr = utils.array_change(area.area[0][0 + ',' + p_id]);
    var c_id = c_arr[columnValue[1]]['id'];
    var a_arr = utils.array_change(area.area[0][0 + ',' + p_id + ',' + c_id]);

    this.setData({
      change_objectMultiArray: [
        p_arr,
        c_arr,
        a_arr
      ],
      change_multiIndex: columnValue
    });
  },

  //选择显示收货地址    有问题，市显示不正确
  // showAddress: function () {
  //   this.setData({
  //     change_objectMultiArray: this.data.objectMultiArray,
  //     change_multiIndex: this.data.multiIndex
  //   });
  // },

  //选择收获地址三级联动后确定按钮动作
  bindMultiPickerChange: function (e) {
    this.addressChange(e.detail.value);

    this.setData({
      objectMultiArray: this.data.change_objectMultiArray,
      multiIndex: e.detail.value
    });
    this.setData({
      'address_info.Address_Province': this.data.objectMultiArray[0][this.data.multiIndex[0]]['id'],
      'address_info.Address_City': this.data.objectMultiArray[1][this.data.multiIndex[1]]['id'],
      'address_info.Address_Area': this.data.objectMultiArray[2][this.data.multiIndex[2]]['id'],
      'address_info.Address_Town': 0,
      t_arr: [],
      t_index: 0
    });

    // 处理街道信息
    this.address_town();
  },

  //选择收货地址
  bindMultiPickerColumnChange: function (e) {
    var column = e.detail.column;  //修改的列
    var index = e.detail.value;    //选择列的下标（从0开始）
    var change_multiIndex = 'change_multiIndex[' + column + ']';

    var columnValue = [
      column == 0 ? index : this.data.change_multiIndex[0],
      column == 0 ? 0 : (column == 1 ? index : this.data.change_multiIndex[1]),
      column == 0 || column == 1 ? 0 : index
    ];
    this.addressChange(columnValue);
  },

  //提交地址
  formSubmit: function (e) {
    var address_info = e.detail.value;
    if (!address_info.Address_Name) {
      wx.showToast({
        title: '请输入收货人名称',
        icon: 'loading'
      });
      return false;
    } else {
      this.setData({
        'address_info.Address_Name': address_info.Address_Name
      });
    }
    if (!address_info.Address_Mobile) {
      wx.showToast({
        title: '请输入收货人电话',
        icon: 'loading'
      });
      return false;
    } else if (!utils.check_mobile(address_info.Address_Mobile)) {
      wx.showModal({
        title: '提示',
        content: '请输入正确的电话号码',
        showCancel: false
      });
      return false;
    } else {
      this.setData({
        'address_info.Address_Mobile': address_info.Address_Mobile
      });
    }
    if (!this.data.address_info.Address_Province || !this.data.address_info.Address_City || !this.data.address_info.Address_Area) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'loading'
      });
      return false;
    }
    if (!this.data.address_info.Address_Town) {
      wx.showToast({
        title: '请选择街道',
        icon: 'loading'
      });
      return false;
    }
    if (!address_info.Address_Detailed) {
      wx.showToast({
        title: '请填写详细的地址',
        icon: 'loading'
      });
      return false;
    } else {
      this.setData({
        'address_info.Address_Detailed': address_info.Address_Detailed
      });
    }
    //是否设置为默认地址
    this.setData({
      'address_info.Address_Is_Default': address_info.Address_Is_Default[0] ? 1 : 0,
      'address_info.act' : 'edit_address'
    });
    
    //提交
    if (this.data.address_info.Address_ID) {
      app.http_req(this.data.address_info, app.globalData.init.api_url, 'POST', this.addeditAddress);
    } else {
      delete this.data.address_info.Address_ID;
      this.setData({
        'address_info.act' : 'add_address'
      })
      app.http_req(this.data.address_info, app.globalData.init.api_url, 'POST', this.addeditAddress);
    }
  },

  //添加、编辑收货地址回调
  addeditAddress: function (res) {
    var that = this;
    if (res.errorCode == 0) {
      var address_id = res.data;  //接口返回的收货地址ID
      //返回来时页面
      wx.showToast({
        title: (that.data.address_info.Address_ID ? '编辑成功' : '添加成功'),
        icon: 'success',
        duration: 2000,
        success: function () {
          if (that.data.address_info.Address_ID) {  //编辑
            //跳回收货地址列表页面  不需操作
          } else {  //添加
            //从提交订单页来的，跳回提交订单页
            if (that.data.from_page == 'checkout') {
              var pages = getCurrentPages();          //获取页面堆栈
              var prevPage = pages[pages.length - 2]; //上一页
              prevPage.setData({
                back_address_id: address_id
              });
            }
            //从地址列表跳转来的，跳回列表页面  不需操作
          }
          //返回上一页
          wx.navigateBack({
            delta: 1
          });
        } 
      });
    } else {
      wx.showModal({
        title: '错误',
        content: res.msg,
        showCancel: false
      })
    }
  },

  //编辑地址时，获取地址信息的回调，初始化地址信息
  setAddressInfo: function (res) {
    if (res.errorCode == 0) {
      wx.setNavigationBarTitle({
        title: '编辑收货地址'
      });

      var addressInfo = res.data[0];
      delete addressInfo['Address_Province_name'];
      delete addressInfo['Address_Province_code'];
      delete addressInfo['Address_City_name'];
      delete addressInfo['Address_City_code'];
      delete addressInfo['Address_Area_name'];
      delete addressInfo['Address_Area_code'];
      delete addressInfo['Address_Town_name'];
      delete addressInfo['Address_Town_code'];

      //初始化地址选择数据
      let objectMultiArray = [
        utils.array_change(area.area[0]['0']),
        utils.array_change(area.area[0]['0,' + addressInfo['Address_Province']]),
        utils.array_change(area.area[0]['0,' + addressInfo['Address_Province'] + ',' + addressInfo['Address_City']])
      ];

      //设置初始显示列
      let multiIndex = [
        utils.get_arr_index(objectMultiArray[0], addressInfo['Address_Province']),
        utils.get_arr_index(objectMultiArray[1], addressInfo['Address_City']),
        utils.get_arr_index(objectMultiArray[2], addressInfo['Address_Area'])
      ];
      this.setData({
        address_info: addressInfo,

        //初始化地址选择数据
        objectMultiArray: objectMultiArray,
        change_objectMultiArray: objectMultiArray,

        //设置初始显示列
        multiIndex: multiIndex,
        change_multiIndex: multiIndex
      });

      // 处理街道信息
      this.address_town();
    } else {
      wx.showModal({
        title: '错误',
        content: res.msg,
        showCancel: false
      })
    }
  },

  //设是否为第一条收获地址状态
  getAddressList: function (res) {
    if ((res.errorCode == 0 && res.data.length <= 0) || res.errorCode == 2) {
      this.setData({
        is_first_add: true
      });
    }
  },

  //页面加载
  load: function () {
    //用户登录检查
    if (!app.globalData.userInfo) {
      app.login('', this.load);
      return false;
    }

    this.setData({
      'address_info.Users_ID': app.globalData.userInfo.Users_ID,
      'address_info.User_ID': app.globalData.userInfo.User_ID
    });
    //如果有Address_ID， 则为编辑
    if (this.data.address_info.Address_ID) {
      var addressArgs = {
        User_ID: app.globalData.userInfo.User_ID,
        Address_ID: this.data.address_info.Address_ID,
        act: 'get_address'
      };
      app.http_req(addressArgs, app.globalData.init.api_url, 'POST', this.setAddressInfo);
    } else {  //添加收货地址  初始化地址选择数据
      //地区数据处理
      let p = utils.array_change(area.area[0]['0']);
      let c = utils.array_change(area.area[0]['0,' + p[0].id]);
      let a = utils.array_change(area.area[0]['0,' + p[0].id + ',' + c[0].id]);
      let objectMultiArray = [p, c, a];
      this.setData({
        objectMultiArray: objectMultiArray,
        change_objectMultiArray: objectMultiArray,
        t_arr: [],
        t_index: 0
      });

      //查询是否是该用户要添加的第一条收货地址
      app.http_req({ User_ID: app.globalData.userInfo.User_ID, act : 'get_address' }, app.globalData.init.api_url, 'POST', this.getAddressList);
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //有addressid 地址编辑
    if (options.addressid) {
      this.setData({
        'address_info.Address_ID': options.addressid
      });
    }
    //页面来源
    if (options.from) {
      this.setData({
        from_page: options.from 
      });
    }
    
    this.load();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  }
})